<?php
namespace app\index\controller;
use think\Controller;
use think\facade\Cache;
use app\index\model\Common;

class Order extends Controller{
    private $Common;
    private $global_set;
    //
    public function initialize() {
        $this->Common = Common::instance();
        $this->global_set = $this->Common->getGlobalSet();
    }
    //保存表单
    public function add(){
        if(!$this->request->isPost()){
            return json(['msg'=>'request is not post'], 403);
        }
        $data = $this->data();
        $verify = $this->verify($data);
        if($verify){
            $this->subErr($data, $verify);
            return $this->alert($verify, $data['link']);
        }
        $return = $this->limit($data);//halt($return);
        if($return){
            $msgArr = [1=>'您的订单我们已收到，无需重复提交表单!', 2=>'您已经被拉入黑名单，禁止再次下单!', 3=>'订单关键字黑名单，禁止下单!'];
            $this->subErr($data, $msgArr[$return]);
            return $this->alert($msgArr[$return], $data['link']);
        }
        $advert = $this->Common->getAdvert($data['aid'], 'xname,mid,toid,telno,url,tips,isuno');
        if(!$advert){
            $msg = '无效的广告名称AID:'.$data['aid'];
            $this->subErr($data, $msg);
            return $this->alert($msg, $data['link']);
        }
        unset($data['aid']);
        $data['mid'] = $advert['mid'];
        $data['xname'] = $advert['xname'];
        if($advert['isuno'] == 1){//页面禁止下单
            $msg = '本页面设置了禁止下单,拒绝!';
            $this->subErr($data, $msg);
            return $this->alert($msg, $data['link']);
        }
        $key = 'o_o';
        if(strpos($data['link'], $key.'=1') !== false){//去除标识
            $data['link'] = str_replace(['&'.$key.'=1', $key.'=1'], '', $data['link']);
        }
        $product = $this->Common->getProductInfo($data['pid']);
        $data['product'] = $product['pname'];
        if($data['product'] == ''){
            $msg = '无效的商品PID:'.$data['pid'];
            $this->subErr($data, $msg);
            return $this->alert($msg, $data['link']);
        }
        unset($data['pid']);
        $oid = db('order')->insertGetId($data);
        if($oid){
            $this->sendMsg($data['telno'], $product['cid']);
            return $this->hdfkSuc($data, $advert, $oid);
        }
        return $this->subFail($data, $advert);
    }
    //表单数据
    private function data(){
        $data = [];
        $data['aid'] = $this->request->post('aid/d', 0);
        $data['pid'] = $this->request->post('pid/a', []);
        $data['cname'] = $this->request->post('cname/s', '');
        $data['telno'] = $this->request->post('telno/s', '');
        $data['province'] = $this->request->post('province/s', '');
        $data['city'] = $this->request->post('city/s', '');
        $data['district'] = $this->request->post('district/s', '');
        $data['address'] = $this->request->post('address/s', '');
        $data['address'] = implode('', [$data['province'], $data['city'], $data['district'], $data['address']]);
        $data['desc'] = $this->request->post('desc/s', '');
        $data['payment'] = $this->request->post('payment/d', 1);
        $data['ip'] = $this->request->post('ip/s', ip());
        $data['agent'] = $this->request->has('agent', 'post') ? $this->request->post('agent/s', '') : $this->request->header('user-agent', '');
        $data['link'] = $this->request->has('link', 'post') ? $this->request->post('link/s', '') : $this->request->server('http_referer', '');
        $data['addtime'] = time();
        return $data;
    }
    //下单限制 0正常1已下过单2IP黑名单3关键字黑名单
    private function limit($data){
        if(strpos($this->global_set['order_white_cname'], $data['cname']) !== false){//名字白名单
            return 0;
        }
        if(strpos($this->global_set['order_block_cname'], $data['cname']) !== false){//姓名黑名单
            return 3;
        }
        if(strpos($this->global_set['order_block_telno'], $data['telno']) !== false){//手机号码黑名单
            return 3;
        }
        if($this->Common->isOrderBlockIp($data['ip'])){//IP黑名单
            return 2;
        }
        $key = md5($data['aid'].$data['cname'].$data['telno'].'x'.implode('-', $data['pid']));//
        $tmp = Cache::get($key);
        if($tmp === false){
            Cache::set($key, 1, $this->global_set['order_time_space']);
            return 0;
        }
        Cache::inc($key);
        return 1;
    }
    //验证选项
    private function verify($data){
        $rule = [
            'aid' => '缺少推广AID',
            'cname' => '姓名不能为空',
            'telno' => '电话号码不能为空',
            'pid' => '未选择商品',
        ];
        foreach($rule as $key => $msg){
            if(!$data[$key]){
                return $msg;
            }
        }
        return false;
    }
    //货到付款
    private function hdfkSuc($data, $advert, $oid){
        $msg = ['cname'=>$data['cname'], 'product'=>$data['product'], 'telno'=>$data['telno']];
        $msg['oid'] = date('ymdHis').'OID'.$oid;
        $msg['address'] = $data['address'];
        $msg['link'] = $advert['url'] == '' ? $data['link'] : $advert['url'];
        $msg['call'] = $advert['telno'];
        $msg['tips'] = trim($advert['tips']) ? $advert['tips'] : $this->global_set['order_receive_tips'];
        $path = env('root_path').'public';
        $msg['path'] = '/tpl/od/'.$this->Common->getOrderTplno($advert['toid']);
        $file = $path.$msg['path'].'/index.html';
        if(!file_exists($file)){
            return $this->error('模板文件未上传~~~o');
        }
        return $this->fetch($file, ['tpl' => $msg]);
    }
    //提交失败
    private function subFail($data, $advert){
        $oid = rand(1000, 9999);
        $dir = env('runtime_path').'failorder/';
        if(!is_dir($dir)){
            mkdir($dir, 0755);
        }
        $file = $dir.date('Y-m-d-H-i').'.ser';
        file_put_contents($file, serialize($data)."\r\n", FILE_APPEND);
        return $this->hdfkSuc($data, $advert, $oid);
    }
    //保存错误订单
    private function subErr($data, $msg){
        $dir = env('runtime_path').'errororder/';
        if(!is_dir($dir)){
            mkdir($dir, 0755);
        }
        $file = $dir.date('Y-m-d').'.ser';
        file_put_contents($file, serialize(['msg'=>$msg, 'data'=>$data])."\r\n", FILE_APPEND);
    }
    //提示信息
    private function alert($msg, $url){
        $str = '<script type="text/javascript">alert("'.$msg.'");window.location.href = "'.$url.'";</script>';
        $header = 'Content-type: text/html; charset=utf-8';
        return response($str)->header($header);
    }
    //异步调用短信发送接口
    private function sendMsg($telno, $cid){
        if(strlen($telno) != 11 || !is_numeric($telno)){
            return false;
        }
        $arr = ['11111111111','12222222222','13333333333','14444444444','15555555555','16666666666','17777777777','18888888888','19999999999'];
        if(in_array($telno, $arr)){
            return false;
        }
        $tmid = db('category')->where('cid', '=', $cid)->value('tmid');
        if($tmid){
            $tplmsg = db('tpl_msg')->where('tmid', '=', $tmid)->find();
            if(!$tplmsg){
                return false;
            }
            $nowtime = time();
            $nowdate = date('Y-m-d');
            $xfromtime = strtotime($nowdate.' '.$tplmsg['xfrom'].':00');
            $xtotime = strtotime($nowdate.' '.$tplmsg['xto'].':00');
            if($nowtime >= $xfromtime && $nowtime < $xtotime){
                $msg = $tplmsg['xmsg'];
            }else{
                $msg = $tplmsg['msg'];
            }
            if($tplmsg['platform'] == 'yunpian'){
                $apikey = config('app.yunpian_apikey');
                $result = \app\index\model\Yunpian::instance($apikey)->send($telno, $msg);
                return $result;
            }
        }
        return false;
    }
}